package com.happy_lab_management.demo.admin.user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.happy_lab_management.result.Result;
import com.happy_lab_management.util.JwtUtil;
import com.happy_lab_management.demo.admin.user.mapper.UserMapper;
import com.happy_lab_management.entity.Student;
import com.happy_lab_management.demo.admin.user.service.StudentService;
import com.happy_lab_management.entity.Teacher;
import com.happy_lab_management.demo.admin.user.service.TeacherService;
import com.happy_lab_management.entity.Technician;
import com.happy_lab_management.demo.admin.user.service.TechnicianService;
import com.happy_lab_management.entity.DTO.UserDTO;
import com.happy_lab_management.entity.User;
import com.happy_lab_management.demo.admin.user.service.UserService;
import com.happy_lab_management.properties.JwtProperties;
import com.happy_lab_management.util.PasswordUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserService userService;
    @Autowired
    private TechnicianService technicianService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private UserMapper userMapper;

    /**
     * 分页列表查询所有用户
     */
    @PostMapping("/list")
    public Result<IPage<User>> list(@RequestBody User user,
                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (user.getName() != null)
            queryWrapper.like("name", user.getName());
        if (user.getRoleId() != null)
            queryWrapper.eq("role_id", user.getRoleId());
        if(user.getAccount() !=null)
            queryWrapper.like("account",user.getAccount());
        if(user.getUserId() !=null){
            queryWrapper.eq("user_id",user.getAccount());
        }
        // You need to handle Date fields differently as per your requirements

        Page<User> page = new Page<>(pageNo, pageSize);
        IPage<User> pageList = userService.page(page, queryWrapper);
        return Result.success(pageList);
    }
    /**
     * 分页列表查询所有用户,
     * userId,name,account支持模糊查询，相等查询eq：role_id
     * 该接口耦合度大，更改User相关的数据项时应该检查该接口
     */
    @PostMapping("/findUserDTOPage")
    public Result<IPage<UserDTO>> findUserDTOPage(@RequestBody User user,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize
    ) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if(user.getUserId()!=null)
            queryWrapper.like("user_id",user.getUserId());
        if (user.getName() != null)
            queryWrapper.like("name", user.getName());
        if(user.getAccount() !=null)
            queryWrapper.like("account",user.getAccount());
        if (user.getRoleId() != null)
            queryWrapper.eq("role_id", user.getRoleId());

        Page<User> page = new Page<>(pageNo, pageSize);
        //获取分页的user对象
        IPage<User> pageList = userService.page(page, queryWrapper);
        //下面可以写在UserService中
        Page<UserDTO> dtoPage = new Page<>();
        dtoPage.setTotal(pageList.getTotal());
        dtoPage.setCurrent(pageList.getCurrent());
        dtoPage.setSize(pageList.getSize());
        //将上面的user转换成UserDTO
        List<UserDTO> dtoList = pageList.getRecords().stream().map(userItem ->{
            Integer selectRoleId=userItem.getRoleId();
            Integer selectUserId = userItem.getUserId();
            UserDTO dto = new UserDTO();
            BeanUtils.copyProperties(userItem, dto);
            //请不要返回密码回去前端
            dto.setPassword(null);
            switch(selectRoleId){
                case 2://查询Technician信息
                    Technician technician = technicianService.selectByUserId(selectUserId);
                    if(technician !=null){
                        log.info(technician.toString());
                        dto.setTitle(technician.getTitle());
                    }
                    break;
                case 3://查询teacher信息并且设置
                    Teacher teacher = teacherService.selectByUserId(selectUserId);
                    if(teacher !=null){
                        log.info(teacher.toString());
                        dto.setTitle(teacher.getTitle());
                    }
                    break;
                case 4://查询学生的信息
                    Student student = studentService.selectByUserId(selectUserId);
                    if(student!=null){
                        log.info(student.toString());
                        dto.setMajor(student.getMajor());
                        dto.setClassname(student.getClassname());
                    }
                default:
                    break;
            }
            return dto;
        }).toList();
        dtoPage.setRecords(dtoList);
        return Result.success(dtoPage);
    }
    /**
     * 测试
     */
    @RequestMapping("/test")
    public Result<String> test(){
        List<User> list = userService.list();
        System.out.println(list);
        return Result.success("test成功");
    }

    /**
     * 用户登录
     * @param user
     * @return
     */
    @RequestMapping("/login")
    public Result<String> login(@RequestBody User user){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", user.getAccount());
        User existingUser = userService.getOne(queryWrapper);
        if (existingUser == null) {
            return Result.error("用户不存在");
        }
        if (!user.getPassword().equals(existingUser.getPassword())) {
            return Result.error("密码错误");
        }

//登录成功后，生成jwt令牌

        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", existingUser.getUserId());
        claims.put("account", existingUser.getAccount());
        claims.put("roleId", existingUser.getRoleId());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        Claims claims1 = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            Integer roleId = (Integer) claims1.get("roleId");
        log.info("该角色id为：{}",roleId);
        return Result.success(token);
    }

    /**
     * 注册
     * 批量导入
     * @param userDTOS
     * @return
     */
    @Transactional
    @RequestMapping("/register")
    public Result<String> insertBatch(@RequestBody List<UserDTO> userDTOS){
        for (UserDTO userDTO : userDTOS) {
            // 查询是否存在相同用户名的用户
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account", userDTO.getAccount());
            User existingUser = userService.getOne(queryWrapper);
            if (existingUser != null) {
                return Result.error("账号重复");
            }
            // 为每个DTO创建一个新的User实体并复制属性
            User user = new User();
            BeanUtils.copyProperties(userDTO, user);
            if(user.getPassword()==null||"".equals(user.getPassword().trim())){
                user.setPassword("12345678");
            }
            user.setPassword(PasswordUtil.encryptPassword(user.getPassword()));
            userMapper.insert(user);
            userDTO.setUserId(user.getUserId());
            log.info("user:{}",user);
            log.info("userDTO:{}",userDTO);
            switch (userDTO.getRoleId()) {
                case 2: // 实验员
                    // 插入实验员表的逻辑
                    Technician technician = new Technician();
                    BeanUtils.copyProperties(userDTO, technician);
                    technicianService.save(technician);
                    break;
                case 3: // 教师
                    // 插入教师表的逻辑
                    Teacher teacher = new Teacher();
                    BeanUtils.copyProperties(userDTO, teacher);
                    teacherService.save(teacher);
                    break;
                case 4: // 学生
                    // 插入学生表的逻辑
                    Student student = new Student();
                    BeanUtils.copyProperties(userDTO, student);
                    studentService.save(student);
                    break;
            }
        }
        return Result.success("用户批量插入成功");
    }
    /**
     * 注册
     * 批量导入
     * @param userDTO
     * @return
     */
    @Transactional
    @RequestMapping("/insertOne")
    public Result<String> insertOne(@RequestBody UserDTO userDTO){
        //检查参数是否齐全
        if(userDTO.getAccount()==null){
            return Result.error("缺少用户账户");
        }
        if(userDTO.getRoleId()==null){
            return Result.error("请选择用户身份");
        }
        if(userDTO.getName()==null){
            return Result.error("缺少用户姓名");
        }
        // 查询是否存在相同用户名的用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", userDTO.getAccount());
        User existingUser = userService.getOne(queryWrapper);
        if (existingUser != null) {
            return Result.error("账号重复");
        }
        // 为每个DTO创建一个新的User实体并复制属性
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        if(user.getPassword()==null||"".equals(user.getPassword().trim())){
            user.setPassword("123");
            userDTO.setPassword("123");
        }
        user.setPassword(PasswordUtil.encryptPassword(user.getPassword()));
        userMapper.insert(user);
        userDTO.setUserId(user.getUserId());
        log.info("user:{}",user);
        log.info("userDTO:{}",userDTO);
        switch (userDTO.getRoleId()) {
            case 2: // 实验员
                // 插入实验员表的逻辑
                Technician technician = new Technician();
                BeanUtils.copyProperties(userDTO, technician);
                technicianService.save(technician);
                break;
            case 3: // 教师
                // 插入教师表的逻辑
                Teacher teacher = new Teacher();
                BeanUtils.copyProperties(userDTO, teacher);
                teacherService.save(teacher);
                break;
            case 4: // 学生
                // 插入学生表的逻辑
                Student student = new Student();
                BeanUtils.copyProperties(userDTO, student);
                studentService.save(student);
                break;
        }

        return Result.success("用户新增成功");
    }

    /**
     * 修改用户信息roleId,userId=>修改
     * 不允许该接口修改密码
     * @param userDTO
     * @return
     */
    @PostMapping("/edit")
    public Result<String> edit(@RequestBody UserDTO userDTO){
        if(userDTO.getRoleId()==null){
            return Result.error("请选择用户身份");
        }
        if(userDTO.getUserId()==null){
            return Result.error("请选择用户");
        }

        switch (userDTO.getRoleId()) {
            case 2: // 实验员
                Technician technician=technicianService.selectByUserId(userDTO.getUserId());
                BeanUtils.copyProperties(userDTO,technician);
                technicianService.updateById(technician);
                break;
            case 3: // 教师
                Teacher teacher=teacherService.selectByUserId(userDTO.getUserId());
                BeanUtils.copyProperties(userDTO,teacher);
                teacherService.updateById(teacher);

                break;
            case 4: // 学生
                Student student=studentService.selectByUserId(userDTO.getUserId());
                BeanUtils.copyProperties(userDTO,student);
                studentService.updateById(student);
                break;
        }
        User user=new User();
        BeanUtils.copyProperties(userDTO,user);
        userService.updateById(user);
        return Result.success("修改成功");
    }
    /**
     * 删除单个
     * @param id
     * @return
     */
    @PostMapping("/delOne")
    @Transactional
    public Result<String> delOne(@RequestParam Integer id){
        //删除角色对应的表数据
        //遍历所有user
            if(id==null){
                return Result.error("请选择要删除的用户");
            }
            User user=userService.getById(id);
            if(user==null){
                return Result.error("用户不存在");
            }
            switch (user.getRoleId()) {
                case 2: // 实验员
                    QueryWrapper<Technician> technicianQueryWrapper = new QueryWrapper<>();
                    technicianQueryWrapper.eq("user_id", user.getUserId());
                    technicianService.remove(technicianQueryWrapper);
                    break;
                case 3: // 教师
                    QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
                    teacherQueryWrapper.eq("user_id", user.getUserId());
                    teacherService.remove(teacherQueryWrapper);
                    break;
                case 4: // 学生
                    QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
                    studentQueryWrapper.eq("user_id", user.getUserId());
                    studentService.remove(studentQueryWrapper);
                    break;
            }

        userService.removeById(id);
        return Result.success("删除用户成功");
    }
    /**
     * 删除单个
     * @param userId
     * @return
     */
    @PostMapping("/getById")
    @Transactional
    public Result<Object> getById(@RequestParam(value="userId") Integer userId){
        //删除角色对应的表数据
        //遍历所有user
        if(userId==null){
            return Result.error("查询用户id为null");
        }
        User user=userService.getById(userId);
        if(user==null){
            return Result.error("用户不存在");
        }
        switch (user.getRoleId()) {
            case 2: // 实验员
                Technician technician = technicianService.getById(user.getUserId());
                return Result.success(technician);
            case 3: // 教师
                Teacher teacher = teacherService.getById(user.getUserId());
                return Result.success(teacher);
            case 4: // 学生
                Student student = studentService.getById(user.getUserId());
                return Result.success(student);
        }
        return Result.error("用户身份不存在");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("/delBatch")
    @Transactional
    public Result<String> deleteBatch(@RequestParam List<Integer> ids){
        //删除角色对应的表数据
        //遍历所有user
        for (Integer id:ids){
            User user=userService.getById(id);

            switch (user.getRoleId()) {
                case 2: // 实验员
                    QueryWrapper<Technician> technicianQueryWrapper = new QueryWrapper<>();
                    technicianQueryWrapper.eq("user_id", user.getUserId());
                    technicianService.remove(technicianQueryWrapper);
                    break;
                case 3: // 教师
                    QueryWrapper<Teacher> teacherQueryWrapper = new QueryWrapper<>();
                    teacherQueryWrapper.eq("user_id", user.getUserId());
                    teacherService.remove(teacherQueryWrapper);
                    break;
                case 4: // 学生
                    QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
                    studentQueryWrapper.eq("user_id", user.getUserId());
                    studentService.remove(studentQueryWrapper);
                    break;
            }
        }
        userService.removeBatchByIds(ids);
        return Result.success("批量删除成功");
    }

    /**
     * 重置密码
     * @param userId
     * @return
     */
    @PostMapping("/resetPassword")
    public Result<String> resetPassword(@RequestParam Integer userId){
         User user= userService.getById(userId);
        switch (user.getRoleId()) {
            case 2: // 实验员
                Technician technician= technicianService.selectByUserId(userId);
                technician.setPassword("123456");
                technicianService.updateById(technician);
                break;
            case 3: // 教师
                Teacher teacher= teacherService.selectByUserId(userId);
                teacher.setPassword("123456");
                teacherService.updateById(teacher);
                break;
            case 4: // 学生
                Student student= studentService.selectByUserId(userId);
                student.setPassword("123456");
                studentService.updateById(student);
                break;

        }
        user.setPassword("123456");
        user.setPassword(PasswordUtil.encryptPassword(user.getPassword()));
        userService.updateById(user);

        return Result.success("重置密码成功");
    }
}
